package edu.whu.assignment8.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.whu.assignment8.dataobject.Product;
import edu.whu.assignment8.dataobject.dto.ProductDto;
import edu.whu.assignment8.mapper.ProductMapper;
import edu.whu.assignment8.service.ProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Product findProductById(int pid) {
        return productMapper.selectById(pid);
    }

    @Override
    public List<Product> findAll() {
        return productMapper.selectList(null);
    }

    @Override
    public int addProduct(Product product) {
        return productMapper.insert(product);
    }

    @Override
    public int deleteProduct(int pid) {
        return productMapper.deleteById(pid);
    }

    @Override
    public int updateProduct(Product product) {
        Product same = productMapper.selectById(product.getPid());
        if(same == null) {
            return -1;  //表示用户不存在
        }
        else {
            return productMapper.updateById(product);
        }
    }

    @Override
    public IPage<Product> findPageAndCondition(int current, int size, Product product) {
        IPage<Product> page = new Page(current,size);
        LambdaQueryWrapper<Product> lwq = new LambdaQueryWrapper<>();

        String pname = product.getPname();
        Double price = product.getPrice();

        if(StringUtils.isNotEmpty(pname)) {
            lwq.like(Product::getPname,pname);
        }
        if(price != null) {
            lwq.lt(Product::getPrice,price);
        }

        productMapper.selectPage(page, lwq);
        return page;
    }

    @Override
    public ProductDto findPSById(int pid) {
        ProductDto result = productMapper.findProductAndSuppliersByPid(pid);
        System.out.println(result);
        return result;
    }
}
